//
//  MessageListViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/9/16.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "MessageListViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "MessageDetail.h"
#import "MessageDetailCell.h"

@interface MessageListViewController ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
    NSMutableArray *_messageDetailList;
    int _positionPage;
}

@end

@implementation MessageListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _positionPage = 1;
        _messageDetailList = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if ([self.messageType isEqualToString:@"00"]) {
        self.title = @"系统消息";
    } else if ([self.messageType isEqualToString:@"01"]) {
        self.title = @"业务消息";
    } else if ([self.messageType isEqualToString:@"02"]) {
        self.title = @"个人消息";
    } else if ([self.messageType isEqualToString:@"04"]) {
        self.title = @"快递接收";
    }
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 10)];
    headerView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = headerView;
    [self getMessageDetailListFromSqlite];
    [self handelNetWorkMethod];
}

- (void)getMessageDetailListFromSqlite {
    NSString *sql = [NSString stringWithFormat:@"WHERE socketType = '%@' ORDER BY receiveTime DESC",self.messageType];
    NSArray *array = [MessageDetail findByCriteria:sql];
    [_messageDetailList addObjectsFromArray:array];
    self.tableView.isShowFooterView = NO;
    [self.tableView reloadData];
    if (_messageDetailList.count > 0) {
        [ToastActivity makeActivity:@"正在加载中..." InView:self.view];
    }
    [self getMessageDetailListSocket];
}

- (void)getMessageDetailListSocket {
    if (_messageDetailList.count <= 0) {
        [self.tableView makeLoading];
    } else {
        [self.tableView makeNone];
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STM2"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.userId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.messageType] length:2];
    NSString *positionString = [NSString stringWithFormat:@"%d",_positionPage];
    [mutableData appendBytes:[SocketMethod checkLegal:positionString] length:16];
    [mutableData appendBytes:[@"10" UTF8String] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [ToastActivity dismissInView:self.view];
    [self.tableView endRefreshPullTableView];
    if ([code isEqualToString:SuccessSocket]) {
        if (_positionPage == 1) {
            [_messageDetailList removeAllObjects];
            NSString *sql = [NSString stringWithFormat:@"WHERE socketType = '%@'",self.messageType];
            [MessageDetail deleteObjectsByCriteria:sql];
        }
        NSString *content = [SocketMethod stringDecryHexData:data];
        DLog(@"content:%@",content);
        NSArray *array = [content componentsSeparatedByString:@"|"];
        int i = 0;
        for (NSString *string in array) {
            if (string.length > 0) {
                MessageDetail *detail = [[MessageDetail alloc] initWithString:string];
                detail.socketType = self.messageType;
                [detail saveOrUpdate];
                [_messageDetailList addObject:detail];
                i ++;
            }
        }
        if (_messageDetailList.count <= 0) {
            NSString *tip = nil;
            if ([self.messageType isEqualToString:@"00"]) {
                tip = @"系统消息";
            } else if ([self.messageType isEqualToString:@"01"]) {
                tip = @"业务消息";
            } else if ([self.messageType isEqualToString:@"02"]) {
                tip = @"个人消息";
            } else if ([self.messageType isEqualToString:@"02"]) {
                tip = @"快递接收消息";
            }
            [self.tableView makeTip:[NSString stringWithFormat:@"无%@",tip]];
        } else {
            self.tableView.backgroundView = nil;
            self.tableView.isShowFooterView = ((i < 10) ? NO : YES);
            [self.tableView reloadData];
        }
    } else {
        if (_messageDetailList.count <= 0) {
            [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getMessageDetailListSocket)];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    if (_messageDetailList.count <= 0) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getMessageDetailListSocket)];
    }
    [DSToast showText:msg InView:self.view];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _messageDetailList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageDetail *detail = [_messageDetailList objectAtIndex:indexPath.row];
    return [MessageDetailCell calculateCellHeight:detail];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"MessageDetailCell";
    MessageDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[MessageDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    MessageDetail *detail = [_messageDetailList objectAtIndex:indexPath.row];
    [cell reloadMessageDetailCell:detail];
    return cell;
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.tableView pullScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.tableView pullscrollViewDidEndDragging:scrollView];
}

#pragma mark PullTableViewDelegate
- (void)startRefreshHeaderView {
    _positionPage = 1;
    [self getMessageDetailListSocket];
}

- (void)startRefreshFooterView {
    _positionPage += 10;
    [self getMessageDetailListSocket];
}

- (void)dealloc {
    _socketRequest = nil;
    _messageDetailList = nil;
}

@end
